﻿using Cysharp.Threading.Tasks;
using Net.Distributed;
using Net.Share;
using Net.System;
using Wordgames;

namespace WordGames.System
{
    public class DBCluster
    {
        public ConsistentHashing<WordgamesDB> Hashing { get; internal set; }
        public readonly DataCacheDictionary<string, DataCacheBase> CacheDict = new();

        public void Init(List<DBConfig> dbConfig)
        {
            Hashing = new();
            foreach (var config in dbConfig)
            {
                AddDBNode(config);
            }
        }

        public void AddDBNode(DBConfig config)
        {
            var wordgamesDB = new WordgamesDB
            {
                BatchSize = config.BatchSize,
                SqlBatchSize = config.SqlBatchSize,
                CommandTimeout = config.CommandTimeout,
            };
            var parts = config.Host.Split(':');
            wordgamesDB.Config.Database = config.DBName;
            wordgamesDB.Config.Server = parts[0];
            wordgamesDB.Config.Port = uint.Parse(parts[1]);
            wordgamesDB.Config.UserID = config.User;
            wordgamesDB.Config.Password = config.Password;
            wordgamesDB.CheckTables(config.Password, config.DBName);
            wordgamesDB.InitTablesId(true, config.MachineId, 10);
            wordgamesDB.Start();
            Hashing.AddNode(config.DBName, wordgamesDB);
        }

        public WordgamesDB GetDBNode(string key)
        {
            return Hashing.GetNode(key).Token;
        }

        public WordgamesDB[] GetDBNodes()
        {
            return Hashing.GetNodes();
        }

        public WordgamesDB GetNodeName(string name)
        {
            return Hashing.GetNodeName(name);
        }

        public DataCacheBase GetCache(string key)
        {
            return CacheDict.GetOrCreate(key);
        }

        public async UniTask<T> QueryAsync<T>(string key, string filterExpression) where T : IDataRow, new()
        {
            return await GetDBNode(key).QueryAsync<T>(filterExpression);
        }
    }
}
